﻿using System.Runtime.CompilerServices;
using System.Threading.Tasks;

namespace System.Threading.Tasks
{
    /// <summary>
    /// Task实例监控器
    /// </summary>
    public class TaskMonitor
    {
        public static Task Run(Action dosomthing,
                [CallerMemberName] string memberName = default,
                [CallerFilePath] string sourceFilePath = default,
                [CallerLineNumber] int sourceLineNumber = default(int)
                )
        {
            Action action = new Action(() =>
            {
                var caller = new CallerMonitor(memberName, sourceFilePath, sourceLineNumber).Start();
                dosomthing();
                caller.Stop();
            });
            return Task.Run(action);
        }

        public static Task Run(Action dosomthing, CancellationToken token,
            [CallerMemberName] string memberName = default,
            [CallerFilePath] string sourceFilePath = default,
            [CallerLineNumber] int sourceLineNumber = default(int)
        )
        {
            Action action = new Action(() =>
            {
                var caller = new CallerMonitor(memberName, sourceFilePath, sourceLineNumber).Start();
                dosomthing();
                caller.Stop();
            });
            return Task.Run(action, token);
        }

        public static Task FactoryStartNewMonitor(Action dosomthing,
                [CallerMemberName] string memberName = default,
                [CallerFilePath] string sourceFilePath = default,
                [CallerLineNumber] int sourceLineNumber = default(int)
                )
        {
            Action action = new Action(() =>
            {
                var caller = new CallerMonitor(memberName, sourceFilePath, sourceLineNumber).Start();
                dosomthing();
                caller.Stop();
            });
            return Task.Factory.StartNew(action);
        }

        public static Task FactoryStartNewMonitorLongRunning(Action dosomthing,
            [CallerMemberName] string memberName = default,
            [CallerFilePath] string sourceFilePath = default,
            [CallerLineNumber] int sourceLineNumber = default(int),
            CancellationToken token = default,
            TaskCreationOptions creationOptions = TaskCreationOptions.LongRunning,
            TaskScheduler scheduler = null
        )
        {
            Action action = new Action(() =>
            {
                var caller = new CallerMonitor(memberName, sourceFilePath, sourceLineNumber).Start();
                dosomthing();
                caller.Stop();
            });
            return Task.Factory.StartNew(action, token, creationOptions, scheduler ?? TaskScheduler.Default);
        }
    }
}
